import redis
from time import sleep

from concurrent.futures import ThreadPoolExecutor

from db import Tthread

class RedisLock():
    def __init__(self,key,expire=60) -> None:
        self.redis = redis.Redis(host='localhost',port=6379,db=0)
        self.key = key
        self.expire = expire
    
    def acquire(self):
        while True:
            result = self.redis.set(self.key,1,ex=self.expire,nx=True)
            if result:
                return True
            sleep(0.01)
    
    def release(self):
        self.redis.delete(self.key)
        
    def __enter__(self):
        self.acquire()
        return self
    
    def __exit__(self,exc_type,exc_val,exc_tb):
        self.release()
        
def get_or_create(thread_id,lock):
    with lock:
        Tthread.get_or_create(thread_id=thread_id)
        
def main():
    redis_lock = RedisLock('my_lock')
    pool = ThreadPoolExecutor(max_workers=3)
    
    for i in range(100):
        pool.submit(get_or_create,i,redis_lock)
        pool.submit(get_or_create,i,redis_lock)
        pool.submit(get_or_create,i,redis_lock)
    pool.shutdown()
    
if __name__=='__main__':
    main()